package sk.tramtatiri;

import java.util.List;
import java.util.Locale;

import org.apache.wicket.Request;
import org.apache.wicket.Session;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.spring.injection.annot.SpringBean;

import sk.tramtatiri.data.dao.interfaces.UserDao;
import sk.tramtatiri.data.dataobjects.User;

public class MySession extends WebSession {

	private static final long serialVersionUID = 1L;
	private Long userID;
	private String userNickname;
	private List<User> users;
	private User loggedUser;

	@SpringBean
	private UserDao userDao;

	public MySession(Request request) {
		super(request);
		InjectorHolder.getInjector().inject(this);
	}

	public boolean login(String userEmail, String password) {
		boolean bool = false;
		users = userDao.findAll();
		for (User u : users) {
			if (u.getEmail().equalsIgnoreCase(userEmail)) {
				if (u.getPassword().equals(
						((WicketApplication) getApplication())
								.hashPassword(password))) {
					this.userID = u.getId();
					this.userNickname = u.getNickName();
					bool = true;
					loggedUser = u;
				}
			}
		}
		return bool;
	}

	public Long getUserID() {
		return userID;
	}

	public String getUserNickname() {
		return userNickname;
	}

	public static MySession get() {
		return (MySession) Session.get();
	}

	public boolean hasPermission() {
		if (this.userID == null)
			return false;
		else
			return true;
	}

	public User getLoggedUser() {
		return loggedUser;
	}

	public void setLoggedUser() {
		this.loggedUser = userDao.load(userID);
	}
}
